package net;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * TCP网络通信编程-客户端
 * (字节流)
 */
public class SocketTCP02Client {

    public static void main(String[] args) throws Exception {

        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println(socket.getClass());

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello, server".getBytes());
        socket.shutdownOutput();//设置写入结束标记

        InputStream inputStream = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int len;
        StringBuilder stringBuilder = new StringBuilder();
        while ((len = inputStream.read(buffer)) != -1) {
            stringBuilder.append(new String(buffer, 0, len));
        }
        if (stringBuilder.toString().equals("hello, client")) {
            System.out.println("接收到服务器响应:" + stringBuilder);
            System.out.println("客户端退出...");
            outputStream.close();
            inputStream.close();
            socket.close();
        }

    }
}
